package com.yequan.redis;

import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

public class RedisDemo {

    private static Jedis jedis = new Jedis("192.168.157.140");

    private static Random random = new Random();

    public static void main(String[] args) {

        long publishTime = System.currentTimeMillis() / 1000;
        ArticleRedis articleRedis = new ArticleRedis();
        List<String> articleIds = publishArticles(articleRedis, 1000);
        for (String articleId : articleIds) {
            System.out.println("******已发布文章: " + articleId + "******");
            if (Integer.parseInt(articleId)%10==3){
                String article = "article:" + articleId;
                Integer beforeArticleVotes = articleRedis.getArticleVotes(jedis, article);
                System.out.println("******文章" + article + "投票前票数为: " + beforeArticleVotes + "******");
                articleRedis.voteArticle(jedis, "二狗子", article);
                Integer afterArticleVotes = articleRedis.getArticleVotes(jedis, article);
                System.out.println("******文章" + article + "投票后票数为: " + afterArticleVotes + "******");
            }
        }

        List<Map<String, String>> articlesByScore = articleRedis.getArticlesByScore(jedis, 1);
        for (Map<String, String> articleMap : articlesByScore) {
            System.out.println(articleMap.get("id") + "___" + articleMap.get("title"));
        }
        System.out.println("----------------------------");
        List<Map<String, String>> articlesByTime = articleRedis.getArticlesByTime(jedis, 1);
        for (Map<String, String> articleMap : articlesByTime) {
            System.out.println(articleMap.get("id") + "___" + articleMap.get("title"));
        }
    }

    public static List<String> publishArticles(ArticleRedis articleRedis, int num) {
        List<String> articleIds = new ArrayList<String>();
        for (int i = 0; i < num; i++) {
            int randomNum = random.nextInt(10000);
            Article articleItem = new Article();
            articleItem.setTitle("发布文章" + randomNum);
            articleItem.setPublisher("叶权");
            articleItem.setLink("http://www.yequan.com");
            long publishTime = (System.currentTimeMillis() / 1000) + randomNum;
            articleItem.setTime(publishTime);
            String articleId = articleRedis.publishArticle(jedis, articleItem);
            articleIds.add(articleId);
        }
        return articleIds.size() > 0 ? articleIds : null;
    }

}
